//package com.example.webrtcproject;
//
//import android.annotation.SuppressLint;
//import android.os.Bundle;
//import android.os.Handler;
//import android.os.Message;
//import android.text.TextUtils;
//import android.util.Log;
//import android.view.View;
//import android.widget.Button;
//import android.widget.EditText;
//import android.widget.TextView;
//
//import com.google.gson.Gson;
//
//import org.java_websocket.client.WebSocketClient;
//import org.java_websocket.drafts.Draft_6455;
//import org.java_websocket.handshake.ServerHandshake;
//import org.webrtc.AudioSource;
//import org.webrtc.AudioTrack;
//import org.webrtc.Camera1Enumerator;
//import org.webrtc.Camera2Enumerator;
//import org.webrtc.CameraEnumerator;
//import org.webrtc.DataChannel;
//import org.webrtc.DefaultVideoDecoderFactory;
//import org.webrtc.DefaultVideoEncoderFactory;
//import org.webrtc.EglBase;
//import org.webrtc.IceCandidate;
//import org.webrtc.Logging;
//import org.webrtc.MediaConstraints;
//import org.webrtc.MediaStream;
//import org.webrtc.PeerConnection;
//import org.webrtc.PeerConnectionFactory;
//import org.webrtc.RendererCommon;
//import org.webrtc.SessionDescription;
//import org.webrtc.SurfaceTextureHelper;
//import org.webrtc.SurfaceViewRenderer;
//import org.webrtc.VideoCapturer;
//import org.webrtc.VideoSource;
//import org.webrtc.VideoTrack;
//
//import java.net.URI;
//import java.nio.ByteBuffer;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import androidx.annotation.NonNull;
//import androidx.appcompat.app.AppCompatActivity;
//
//
///**
// * 界面展示
// * Created by taxiao on 2019/8/17
// * CSDN:http://blog.csdn.net/yin13753884368/article
// * Github:https://github.com/taxiao213
// *
// * https://zhuanlan.zhihu.com/p/82446482
// * 微信公众号:他晓
// */
//public class WebRtcReceiveActivity extends AppCompatActivity implements View.OnClickListener {
//    private static final String TAG = "Call+++++";
//
//    private SurfaceViewRenderer localSurfaceView;
//    private SurfaceViewRenderer remoteSurfaceView;
//    private EglBase eglBase;
//    private PeerConnectionFactory peerConnectionFactory;
//
//    private VideoTrack videoTrack;
//    private AudioTrack audioTrack;
//    private PeerConnection peerConnection;
//    private List<String> streamList;
//    private WebSocketClient webSocketClient;
//    private List<PeerConnection.IceServer> iceServers;
//    private Button btConnect;
//    private Button btCall;
//    private TextView tvIsCall;
//    private Button btReCall;
//    private Button btReFuse;
//    private DataChannel channel;
//    private MySdpObserver observer;
//
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.webrtc_layout);
//        localSurfaceView = findViewById(R.id.LocalSurfaceView);
//        remoteSurfaceView = findViewById(R.id.RemoteSurfaceView);
//        btConnect = findViewById(R.id.bt_connect);
//        btCall = findViewById(R.id.bt_call);
//        tvIsCall = findViewById(R.id.tv_iscall);
//        btReFuse = findViewById(R.id.bt_refuse);
//        btReCall = findViewById(R.id.bt_recall);
//        btConnect.setOnClickListener(this);
//        btCall.setOnClickListener(this);
//        btReCall.setOnClickListener(this);
//        btReFuse.setOnClickListener(this);
//    }
//
//
//    @Override
//    public void onClick(View v) {
//        if (v != null) {
//            switch (v.getId()) {
//                case R.id.bt_connect:
//                    Log.e(TAG, "onClick: 拨打方点击了连接");
//                    connectionWebsocket();
//                    break;
//                case R.id.bt_call:
//                    call();
//                    break;
//                case R.id.bt_refuse:
//                    reFuse();
//                    break;
//                case R.id.bt_recall:
//                    reCall();
//                    break;
//            }
//        }
//    }
//    @SuppressLint("HandlerLeak")
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg != null) {
//                String obj = (String) msg.obj;
//                if (!TextUtils.isEmpty(obj)) {
//                    switch (obj) {
//                        case Constant.OPEN:
//                            createPeerConnection();
//                            break;
//                    }
//                }
//            }
//        }
//    };
//
//    /**
//     * 连接Websocket
//     */
//    private void connectionWebsocket() {
//        try {
//            Map<String, String> map = new HashMap<>();
//            map.put("origin", "http://meet2.2u.chat:8089");
//            webSocketClient = new WebSocketClient(URI.create(Constant.URL), new Draft_6455(), map) {
//                @Override
//                public void onOpen(ServerHandshake handshakedata) {
//                    Log.e(TAG, "webSocketClient: webSocketClient连接成功");
//                    setText("已连接");
//                    Log.e(TAG, "onOpen == Status == " + handshakedata.getHttpStatus() + " StatusMessage == " + handshakedata.getHttpStatusMessage());
//                    Model model = new Model(Constant.REGISTER, Constant.ROOMID, Constant.CLIENTA);
//                    webSocketClient.send(model.toString());
//                }
//
//                @Override
//                public void onMessage(String message) {
//                    Log.e(TAG, "onMessage: ：收到消息：" + message);
//                    if (!TextUtils.isEmpty(message)) {
//                        Model model = new Gson().fromJson(message, Model.class);
//                        if (model != null) {
//                            String eventname = model.getEventname();
//                            Log.e(TAG, "onMessage: ：收到消息：eventName为：" + eventname);
//                            if (!TextUtils.isEmpty(eventname)) {
//                                switch (eventname) {
//                                    case Constant.PEER:
//                                        Message msg = new Message();
//                                        msg.obj = Constant.OPEN;
//                                        handler.sendMessage(msg);
//                                        Log.e(TAG, "onMessage: 拨打方连接成功");
//                                        break;
//                                    case Constant.NEW_PEER:
//                                        Log.e(TAG, "onMessage: 得知接收方连接成功，开始创建SessionDescription");
//                                        createOffer();
//                                        break;
//                                    case Constant.CALL:
//                                        Log.e(TAG, "onMessage: "+"有电话进来");
//                                        isIncall();
//                                        break;
//                                    case Constant.AGREE:
//                                        Log.e(TAG, "onMessage: 得知对方同意接听,开始创建SessionDescription");
//                                        createOffer();
//                                        break;
//                                    case Constant.REFUSE:
//                                        Log.e(TAG, "onMessage: 对方拒绝 接听");
//                                        break;
//                                    case Constant.ICE_CANDIDATE:
//                                        //接收方收到对方发来的SessionDescription，开始做出应答
//                                        Log.e(TAG, "onMessage: 收到关于SessionDescription的消息");
//                                        SessionDescription sessionDescription1 = model.getSessionDescription();
//                                        peerConnection.setRemoteDescription(observer, sessionDescription1);
//                                        createAnswer();
//                                        break;
//                                    case Constant.CANDIDATE:
//                                        //服务端 发送 接收方sdpAnswer
//                                        Log.e(TAG, "onMessage: 收到Constant.CANDIDATE消息+++++");
//                                        WebMessage webMessage = new Gson().fromJson(model.getMsg(),WebMessage.class);
//                                        IceCandidate iceCandidate = webMessage.getIceCandidate();
//                                        if (iceCandidate != null) {
//                                            peerConnection.addIceCandidate(iceCandidate);
//                                        }
//                                        break;
//                                }
//                            }
//                        }
//                    }
//                }
//
//                @Override
//                public void onClose(int code, String reason, boolean remote) {
//                    setText("已关闭");
//                    Log.e(TAG, "onClose == code " + code + " reason == " + reason + " remote == " + remote);
//                }
//
//                @Override
//                public void onError(Exception ex) {
//                    setText("onError == " + ex.getMessage());
//                    Log.e(TAG, "onError== " + ex.getMessage());
//                }
//            };
//            webSocketClient.connect();
//        } catch (Exception e) {
//            e.printStackTrace();
//            Log.d(TAG, "socket Exception : " + e.getMessage());
//        }
//    }
//
//
//    /**
//     * 连接webrtc
//     */
//    private void createPeerConnection() {
//        //Initialising PeerConnectionFactory
//        PeerConnectionFactory.InitializationOptions initializationOptions = PeerConnectionFactory.InitializationOptions.builder(this)
//                .setEnableInternalTracer(true)
//                .setFieldTrials("WebRTC-H264HighProfile/Enabled/")
//                .createInitializationOptions();
//        PeerConnectionFactory.initialize(initializationOptions);
//        //创建EglBase对象
//        eglBase = EglBase.create();
//        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
//        options.disableEncryption = true;
//        options.disableNetworkMonitor = true;
//        peerConnectionFactory = PeerConnectionFactory.builder()
//                .setVideoDecoderFactory(new DefaultVideoDecoderFactory(eglBase.getEglBaseContext()))
//                .setVideoEncoderFactory(new DefaultVideoEncoderFactory(eglBase.getEglBaseContext(), true, true))
//                .setOptions(options)
//                .createPeerConnectionFactory();
//        // 配置STUN穿透服务器  转发服务器
//        iceServers = new ArrayList<>();
//        PeerConnection.IceServer iceServer = PeerConnection.IceServer.builder(Constant.STUN).createIceServer();
//        iceServers.add(iceServer);
//
//        streamList = new ArrayList<>();
//
//        PeerConnection.RTCConfiguration configuration = new PeerConnection.RTCConfiguration(iceServers);
//
//        PeerConnectionObserver connectionObserver = getObserver();
//        peerConnection = peerConnectionFactory.createPeerConnection(configuration, connectionObserver);
//
//
//        /*
//        DataChannel.Init 可配参数说明：
//        ordered：是否保证顺序传输；
//        maxRetransmitTimeMs：重传允许的最长时间；
//        maxRetransmits：重传允许的最大次数；
//        */
//        DataChannel.Init init = new DataChannel.Init();
//        if (peerConnection != null) {
//            channel = peerConnection.createDataChannel(Constant.CHANNEL, init);
//        }
//        DateChannelObserver channelObserver = new DateChannelObserver();
//        connectionObserver.setObserver(channelObserver);
//        initView();
//        initObserver();
//    }
//
//    private void initObserver() {
//        observer = new MySdpObserver() {
//            @Override
//            public void onCreateSuccess(SessionDescription sessionDescription) {
//                //将会话描述设置在本地
//                peerConnection.setLocalDescription(this, sessionDescription);
//                SessionDescription localDescription = peerConnection.getLocalDescription();
//                SessionDescription.Type type = localDescription.type;
//                Log.e(TAG, "onCreateSuccess " + " SessionDescription创建成功，type为：" + type);
//                //接下来使用之前的WebSocket实例将offer发送给服务器
//                if (type == SessionDescription.Type.OFFER) {
//                    //呼叫
//                    offer(sessionDescription);
//                } else if (type == SessionDescription.Type.ANSWER) {
//                    //应答
//                    answer(sessionDescription);
//                } else if (type == SessionDescription.Type.PRANSWER) {
//                    //再次应答
//
//                }
//            }
//        };
//
//    }
//
//    @NonNull
//    private PeerConnectionObserver getObserver() {
//        return new PeerConnectionObserver() {
//            @Override
//            public void onIceCandidate(IceCandidate iceCandidate) {
//                super.onIceCandidate(iceCandidate);
//                Log.e(TAG, "onIceCandidate回调成功，并开始调用setIceCandidate()");
//                setIceCandidate(iceCandidate);
//            }
//
//            @Override
//            public void onAddStream(MediaStream mediaStream) {
//                super.onAddStream(mediaStream);
//                Log.d(TAG, "onAddStream : " + mediaStream.toString());
//                List<VideoTrack> videoTracks = mediaStream.videoTracks;
//                if (videoTracks != null && videoTracks.size() > 0) {
//                    VideoTrack videoTrack = videoTracks.get(0);
//                    if (videoTrack != null) {
//                        videoTrack.addSink(remoteSurfaceView);
//                    }
//                }
//                List<AudioTrack> audioTracks = mediaStream.audioTracks;
//                if (audioTracks != null && audioTracks.size() > 0) {
//                    AudioTrack audioTrack = audioTracks.get(0);
//                    if (audioTrack != null) {
//                        audioTrack.setVolume(Constant.VOLUME);
//                    }
//                }
//            }
//        };
//    }
//
//    private void sendMessage(String message) {
//        byte[] msg = message.getBytes();
//        DataChannel.Buffer buffer = new DataChannel.Buffer(ByteBuffer.wrap(msg), false);
//        channel.send(buffer);
//    }
//
//    /**
//     * 初始化view
//     */
//    private void initView() {
//        initSurfaceview(localSurfaceView);
//        initSurfaceview(remoteSurfaceView);
//        startLocalVideoCapture(localSurfaceView);
//        startLocalAudioCapture();
//    }
//
//    /**
//     * 创建本地视频
//     *
//     * @param localSurfaceView
//     */
//    private void startLocalVideoCapture(SurfaceViewRenderer localSurfaceView) {
//        VideoSource videoSource = peerConnectionFactory.createVideoSource(true);
//        SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create(Thread.currentThread().getName(), eglBase.getEglBaseContext());
//        VideoCapturer videoCapturer = createVideoCapturer();
//        videoCapturer.initialize(surfaceTextureHelper, this, videoSource.getCapturerObserver());
//        videoCapturer.startCapture(Constant.VIDEO_RESOLUTION_WIDTH, Constant.VIDEO_RESOLUTION_HEIGHT, Constant.VIDEO_FPS); // width, height, frame per second
//        videoTrack = peerConnectionFactory.createVideoTrack(Constant.VIDEO_TRACK_ID, videoSource);
//        videoTrack.addSink(localSurfaceView);
//        MediaStream videoStream = peerConnectionFactory.createLocalMediaStream(Constant.LOCAL_VIDEO_STREAM);
//        videoStream.addTrack(videoTrack);
//        peerConnection.addTrack(videoTrack, streamList);
//        peerConnection.addStream(videoStream);
//    }
//
//    /**
//     * 创建本地音频
//     */
//    private void startLocalAudioCapture() {
//        //语音
//        MediaConstraints audioConstraints = new MediaConstraints();
//        //回声消除
//        audioConstraints.mandatory.add(new MediaConstraints.KeyValuePair("googEchoCancellation", "true"));
//        //自动增益
//        audioConstraints.mandatory.add(new MediaConstraints.KeyValuePair("googAutoGainControl", "true"));
//        //高音过滤
//        audioConstraints.mandatory.add(new MediaConstraints.KeyValuePair("googHighpassFilter", "true"));
//        //噪音处理
//        audioConstraints.mandatory.add(new MediaConstraints.KeyValuePair("googNoiseSuppression", "true"));
//        AudioSource audioSource = peerConnectionFactory.createAudioSource(audioConstraints);
//        audioTrack = peerConnectionFactory.createAudioTrack(Constant.AUDIO_TRACK_ID, audioSource);
//        MediaStream videoStream = peerConnectionFactory.createLocalMediaStream(Constant.LOCAL_AUDIO_STREAM);
//        videoStream.addTrack(audioTrack);
//        audioTrack.setVolume(Constant.VOLUME);
//        peerConnection.addTrack(audioTrack, streamList);
//        peerConnection.addStream(videoStream);
//    }
//
//    /**
//     * 初始化iew
//     *
//     * @param localSurfaceView
//     */
//    private void initSurfaceview(SurfaceViewRenderer localSurfaceView) {
//        localSurfaceView.init(eglBase.getEglBaseContext(), null);
//        localSurfaceView.setMirror(true);
//        localSurfaceView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL);
//        localSurfaceView.setKeepScreenOn(true);
//        localSurfaceView.setZOrderMediaOverlay(true);
//        localSurfaceView.setEnableHardwareScaler(false);
//    }
//
//
//    /**
//     * 拨打电话 开始创建SessionDescription：
//     */
//    private void createOffer() {
//        Log.e(TAG, "createOffer: "+"拨打方开始创建SessionDescription");
//        MediaConstraints mediaConstraints = new MediaConstraints();
//        mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
//        peerConnection.createOffer(observer, mediaConstraints);
//    }
//    /**
//     * 拨打方创建完SessionDescription后开始发送SessionDescription
//     *
//     * @param sdpDescription
//     */
//    private void offer(SessionDescription sdpDescription) {
//        Log.e(TAG, "offer: SessionDescription："+"拨打方开始发送SessionDescription");
//        Model model = new Model(Constant.SEND, Constant.ROOMID, Constant.CLIENTB);
//        model.setEventname(Constant.ICE_CANDIDATE);
//        WebMessage webMessage = new WebMessage();
//        webMessage.setCandidate(sdpDescription);
//        model.setMsg(webMessage.toString());
//        String text = model.toString();
//        webSocketClient.send(text);
//        Log.e(TAG, "offer() " + "发送SessionDescription成功");
//    }
//    private void createAnswer() {
//        Log.e(TAG, "createAnswer: "+"收到SessionDescription后做出响应继续创建SessionDescription");
//        MediaConstraints mediaConstraints = new MediaConstraints();
//        mediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
//        peerConnection.createAnswer(observer, mediaConstraints);
//    }
//    /**
//     *
//     *  接收方收到对方发来的SessionDescription开始做出响应
//     * @param sdpDescription
//     */
//    private void answer(SessionDescription sdpDescription) {
//        Log.e(TAG, "answer: SessionDescription："+"接收方收到对方发来的SessionDescription开始做出响应");
//        Model model = new Model(Constant.SEND, Constant.ROOMID, Constant.CLIENTB);
//        model.setEventname(Constant.ICE_CANDIDATE);
//        WebMessage webMessage = new WebMessage();
//        webMessage.setCandidate(sdpDescription);
//        model.setMsg(webMessage.toString());
//        String text = new Gson().toJson(model);
//        webSocketClient.send(text);
//    }
//
//
//    /**
//     * 呼叫
//     *
//     * @param iceCandidate
//     */
//    private void setIceCandidate(IceCandidate iceCandidate) {
//        Log.e(TAG, "setIceCandidate: 发送了Constant.CANDIDATE消息");
//        Model model = new Model(Constant.SEND, Constant.ROOMID, Constant.CLIENTA);
//        model.setEventname(Constant.CANDIDATE);
//        WebMessage webMessage = new WebMessage();
//        webMessage.setIceCandidate(iceCandidate);
//        model.setMsg(webMessage.toString());
//        webSocketClient.send(model.toString());
//    }
//
//    /**
//     * 呼叫
//     */
//    private void call() {
//        Log.e(TAG, "call(): 拨打方点击了拨打");
//        Model model = new Model(Constant.SEND, Constant.ROOMID, Constant.CLIENTB);
//        model.setEventname(Constant.CALL);
//        WebMessage webMessage = new WebMessage();
//        webMessage.setId("client_a");
//        model.setMsg(webMessage.toString());
//        String content = model.toString();
//        Log.d(TAG, "call : " + content);
//        webSocketClient.send(content);
//    }
//
//    /**
//     * 是否接听
//     */
//    private void isIncall() {
//        ToastUtil.showToast(this,"收到来电，是否接听");
//    }
//
//    /**
//     * 接听
//     */
//    private void reCall() {
//        Log.e(TAG, "reCall: 接听了电话" );
//        Model model = new Model(Constant.SEND, Constant.ROOMID, Constant.CLIENTA);
//        model.setEventname(Constant.AGREE);
//        WebMessage webMessage = new WebMessage();
//        webMessage.setEventname(Constant.AGREE);
//        model.setMsg(webMessage.toString());
//        webSocketClient.send(model.toString());
//    }
//
//    /**
//     * 拒绝
//     */
//    private void reFuse() {
//        Log.e(TAG, "reFuse: 拒绝了电话");
//        Model model = new Model(Constant.SEND, Constant.ROOMID, Constant.CLIENTA);
//        model.setEventname(Constant.REFUSE);
//        WebMessage webMessage = new WebMessage();
//        webMessage.setEventname(Constant.REFUSE);
//        model.setMsg(webMessage.toString());
//        webSocketClient.send(model.toString());
//    }
//
//
//    private void setText(final String st) {
//        runOnUiThread(() -> btConnect.setText(st));
//    }
//
//    /**
//     * 准备摄像头
//     *
//     * @return
//     */
//    private VideoCapturer createVideoCapturer() {
//        if (Camera2Enumerator.isSupported(this)) {
//            return createCameraCapturer(new Camera2Enumerator(this));
//        } else {
//            return createCameraCapturer(new Camera1Enumerator(true));
//        }
//    }
//
//    private VideoCapturer createCameraCapturer(CameraEnumerator enumerator) {
//        final String[] deviceNames = enumerator.getDeviceNames();
//
//        // First, try to find front facing camera
//        Log.d(TAG, "Looking for front facing cameras.");
//        for (String deviceName : deviceNames) {
//            if (enumerator.isFrontFacing(deviceName)) {
//                Logging.d(TAG, "Creating front facing camera capturer.");
//                VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
//                if (videoCapturer != null) {
//                    return videoCapturer;
//                }
//            }
//        }
//
//        // Front facing camera not found, try something else
//        Log.d(TAG, "Looking for other cameras.");
//        for (String deviceName : deviceNames) {
//            if (!enumerator.isFrontFacing(deviceName)) {
//                Logging.d(TAG, "Creating other camera capturer.");
//                VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
//                if (videoCapturer != null) {
//                    return videoCapturer;
//                }
//            }
//        }
//        return null;
//    }
//
//    private void close() {
//        if (peerConnection != null) {
//            peerConnection.close();
//        }
//        if (webSocketClient != null) {
//            webSocketClient.close();
//        }
//        if (localSurfaceView != null) {
//            localSurfaceView.release();
//        }
//        if (remoteSurfaceView != null) {
//            remoteSurfaceView.release();
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        close();
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        close();
//    }
//}
